package com.ding.controller;

import java.io.File;
import java.io.IOException;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ding.exception.RegisterException;
import com.ding.pojo.User;

@Controller
public class UserController {

	Model model;
	
	@ModelAttribute //控制器方法执行前调用
	public void modelAtrrabute(Model model) {
		this.model=model;
	}
	
	@RequestMapping(value="/register",method=RequestMethod.GET)
	public String registerGet(Model m) {
		
		m.addAttribute(new User());
		return "register";
		
	}
	
	final File tmp=new File("C:\\Users\\逆游的鱼\\Desktop\\tmp\\pic");
	
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String registerPost(RedirectAttributes m, @RequestPart("picture") MultipartFile part,@Valid User user,Errors errors) throws Throwable, IOException {
		
		if (part==null) {
			throw new RegisterException("必须上传图片");
		}
		
		if (errors.hasErrors()) {
			return "register";
		}
		
		File tempFile = File.createTempFile("SpringMVC-temp-",part.getOriginalFilename() , tmp);
		
		part.transferTo(tempFile);
		user.setImgDir("pic/"+tempFile.getName());
		//Flash属性即Session属性,能够跨请求传值
		m.addFlashAttribute(user);
		return "redirect:/user";
	}
	
	@RequestMapping(value="/user",method=RequestMethod.GET)
	public String userGet() {
		return "user"; 
		
	}
	
}
